package com.wlcorp.forcazamis.exception;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;


public abstract class ExceptionHandle {
	protected final Logger log = Logger.getLogger(this.getClass().getName());

    public ActionForward execute(ErrorSaveable action,
            final ActionMapping mapping, final ActionForm form,
            final HttpServletRequest request, final HttpServletResponse response) {
        try {
            ActionForward success = run();
            if(log.isDebugEnabled()){
                log.debug("return forward:"+success);
            }
            return success;
        } catch (Exception e) {
            log.error("catch exceptioin:",e);
            return handleException(action, mapping, request, e);
        } finally {
            afterExcetue(mapping, form, request, response);
        }
    }

    /**
     * @method afterExcetue
     * @param mapping
     * @param form
     * @param request
     * @param response
     * @function afterExcetue
     */
    protected void afterExcetue(ActionMapping mapping, ActionForm form,
            HttpServletRequest request, HttpServletResponse response) {

    }
    
    /**
     * @method stackToString
     * @param e
     * @return String
     * @function stackToString
     */ 
    protected String stackToString(Exception e)
    {
    	StackTraceElement[] steArray = e.getStackTrace();
    	String result = e.toString() + "------";
    	for(int i = 0; i < steArray.length; i++)
    	{
    		result += steArray[i].toString();    		
    	}
    	return result;
    }

    /**
     * @method handleException
     * @param action
     * @param mapping
     * @param request
     * @param e
     * @return ActionForward
     * @function handleException
     */
    protected ActionForward handleException(ErrorSaveable action,
            ActionMapping mapping, final HttpServletRequest request, Exception e) {
//        ActionErrors errors = new ActionErrors();
//        if (e instanceof ServletException) {
//			return new ActionForward("/main.do?method=welcome");			
//		}
    	e.printStackTrace();
        request.setAttribute("errors",stackToString(e));
//        errors.add(ActionErrors.GLOBAL_MESSAGE, new ActionMessage(stackToString(e)));
//        action.saveErrorMessages(request, errors);
        return mapping.findForward("unknown-error");

    }

    /**
     * @method run
     * @return ActionForward
     * @throws Exception
     * @function run
     */
    public abstract ActionForward run() throws Exception;
}
